package com.linkage.jz.bankruptcy.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.linkage.jz.bankruptcy.R;

import java.util.List;


/**
 * @author AFAP
 * 右上角的弹出菜单
 */
public class CommonPopupMenu extends PopupWindow {

    private Activity mActivity;
    private List<String> menuStrList;

    private LinearLayout popView;

    private OnItemClickListener onItemClickListener;

    public CommonPopupMenu(Activity context, List<String> menus) {
        mActivity = context;
        menuStrList = menus;

        popView = (LinearLayout) View.inflate(mActivity, R.layout.common_popup_menu, null);
        this.setContentView(popView);// 把布局文件添加到popupwindow中
        this.setWidth(dip2px(mActivity, 120));
        this.setHeight(LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);// 获取焦点
        this.setTouchable(true); // 设置PopupWindow可触摸
        this.setOutsideTouchable(true); // 设置非PopupWindow区域可触摸
        ColorDrawable dw = new ColorDrawable(0x00000000);
        this.setBackgroundDrawable(dw);

        for (int i = 0; i < menuStrList.size(); i++) {
            final int index = i;
            View v = View.inflate(mActivity, R.layout.common_popup_menu_item, null);
            TextView tv = v.findViewById(R.id.menu_name);
            tv.setText(menuStrList.get(i));
            v.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onClick(index, menuStrList.get(index));
                    }
                }
            });
            popView.addView(v);
        }
    }

    /**
     * 设置显示的位置
     *
     * @param resourId 这里的x,y值自己调整可以
     */
    public void showLocation(int resourId) {
        showLocation(mActivity.findViewById(resourId));
    }

    public void showLocation(View targetView) {
        showAsDropDown(targetView, dip2px(mActivity, 0), dip2px(mActivity, -8));
    }


    // dip转换为px
    public int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    // 点击监听接口
    public interface OnItemClickListener {
        public void onClick(int index, String str);
    }

    // 设置监听
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

}
